package com.aipartner.controller;

import com.aipartner.common.Result;
import com.aipartner.dto.AiImageRequest;
import com.aipartner.dto.AiImageResponse;
import com.aipartner.entity.AiImageExample;
import com.aipartner.entity.AiImageHistory;
import com.aipartner.entity.AiImageExampleLike;
import com.aipartner.service.AiImageService;
import com.aipartner.util.UserContext;
import com.aipartner.mapper.AiImageExampleLikeMapper;
import com.aipartner.mapper.AiImageExampleMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.web.multipart.MultipartFile;

/**
 * AI图片生成控制器
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Slf4j
@RestController
@RequestMapping("/api/ai-image")
@Api(tags = "AI图片生成")
@Validated
public class AiImageController {
    
    @Autowired
    private AiImageService aiImageService;
    
    @Autowired
    private AiImageExampleLikeMapper exampleLikeMapper;
    
    @Autowired
    private AiImageExampleMapper exampleMapper;
    
    /**
     * 上传参考图
     */
    @PostMapping("/upload-reference")
    @ApiOperation("上传参考图")
    public Result<Map<String, String>> uploadReferenceImage(@RequestParam("image") MultipartFile file) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.fail("文件不能为空");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || (!contentType.startsWith("image/"))) {
                return Result.fail("只支持图片文件");
            }
            
            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.fail("文件大小不能超过5MB");
            }
            
            log.info("用户 {} 上传参考图: {}, 大小: {}KB", userId, file.getOriginalFilename(), file.getSize() / 1024);
            
            // 调用服务上传文件
            String imageUrl = aiImageService.uploadReferenceImage(file, userId);
            
            Map<String, String> result = new HashMap<>();
            result.put("imageUrl", imageUrl);
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("上传参考图失败", e);
            return Result.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 生成图片
     */
    @PostMapping("/generate")
    @ApiOperation("生成图片")
    public Result<AiImageResponse> generateImage(@Valid @RequestBody AiImageRequest request) {
        Long userId = UserContext.getCurrentUserId();
        request.setUserId(userId);
        
        log.info("User {} generating image with prompt: {}", userId, request.getPrompt());
        log.info("📥 Controller接收到的referenceImagePath: {}", request.getReferenceImagePath());
        
        AiImageResponse response = aiImageService.generateImage(request);
        return Result.success(response);
    }
    
    /**
     * 查询任务状态
     */
    @GetMapping("/status/{taskId}")
    @ApiOperation("查询任务状态")
    public Result<AiImageResponse> queryTaskStatus(
            @ApiParam("任务ID") @PathVariable @NotBlank String taskId) {
        
        log.info("Querying task status: {}", taskId);
        
        AiImageResponse response = aiImageService.queryTaskStatus(taskId);
        return Result.success(response);
    }
    
    /**
     * 获取示例图片（包含系统示例和用户作品）
     */
    @GetMapping("/examples")
    @ApiOperation("获取示例图片")
    public Result<List<AiImageExample>> getExamples() {
        List<AiImageExample> examples = aiImageService.getExamplesWithUserWorks();
        return Result.success(examples);
    }
    
    /**
     * 获取固定系统示例图片（不包含用户作品）
     */
    @GetMapping("/system-examples")
    @ApiOperation("获取固定系统示例图片")
    public Result<List<AiImageExample>> getSystemExamples() {
        List<AiImageExample> examples = aiImageService.getSystemExamples();
        return Result.success(examples);
    }
    
    /**
     * 获取所有图片（系统示例 + 用户作品） - 统一接口
     */
    @GetMapping("/all-images")
    @ApiOperation("获取所有图片（系统示例和用户作品）")
    public Result<List<AiImageExample>> getAllImages() {
        List<AiImageExample> allImages = aiImageService.getAllImages();
        return Result.success(allImages);
    }
    
    /**
     * 获取用户历史记录
     */
    @GetMapping("/history")
    @ApiOperation("获取用户历史记录")
    public Result<Page<AiImageHistory>> getUserHistory(
            @ApiParam("页码") @RequestParam(defaultValue = "1") @Positive Integer page,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") @Positive Integer size) {
        
        Long userId = UserContext.getCurrentUserId();
        log.info("Getting user {} history, page: {}, size: {}", userId, page, size);
        
        Page<AiImageHistory> result = aiImageService.getUserHistory(userId, page, size);
        return Result.success(result);
    }
    
    /**
     * 获取历史记录详情
     */
    @GetMapping("/history/{id}")
    @ApiOperation("获取历史记录详情")
    public Result<AiImageHistory> getHistoryById(
            @ApiParam("记录ID") @PathVariable @Positive Long id) {
        
        Long userId = UserContext.getCurrentUserId();
        AiImageHistory history = aiImageService.getHistoryById(id, userId);
        
        if (history == null) {
            return Result.fail("记录不存在");
        }
        
        return Result.success(history);
    }
    
    /**
     * 删除历史记录
     */
    @DeleteMapping("/history/{id}")
    @ApiOperation("删除历史记录")
    public Result<Void> deleteHistory(@ApiParam("记录ID") @PathVariable @Positive Long id) {
        Long userId = UserContext.getCurrentUserId();
        log.info("User {} deleting history record: {}", userId, id);
        
        boolean deleted = aiImageService.deleteHistory(id, userId);
        if (deleted) {
            return Result.success(null, "删除成功");
        } else {
            return Result.fail("删除失败，记录不存在或无权限");
        }
    }
    
    /**
     * 通过taskId删除历史记录（临时方案）
     */
    @DeleteMapping("/history/by-task/{taskId}")
    @ApiOperation("通过taskId删除历史记录")
    public Result<Void> deleteHistoryByTaskId(@ApiParam("任务ID") @PathVariable String taskId) {
        Long userId = UserContext.getCurrentUserId();
        log.info("User {} deleting history record by taskId: {}", userId, taskId);
        
        boolean deleted = aiImageService.deleteHistoryByTaskId(taskId, userId);
        if (deleted) {
            return Result.success(null, "删除成功");
        } else {
            return Result.fail("删除失败，记录不存在或无权限");
        }
    }
    
    /**
     * 调试：查看用户的所有历史记录ID
     */
    @GetMapping("/debug/user-records")
    @ApiOperation("调试：查看用户的所有历史记录ID")
    public Result<List<Long>> debugUserRecords() {
        Long userId = UserContext.getCurrentUserId();
        log.info("调试：查询用户 {} 的所有历史记录", userId);
        
        Page<AiImageHistory> result = aiImageService.getUserHistory(userId, 1, 100);
        List<Long> recordIds = result.getRecords().stream()
                .map(AiImageHistory::getId)
                .collect(java.util.stream.Collectors.toList());
        
        log.info("用户 {} 的历史记录ID列表: {}", userId, recordIds);
        return Result.success(recordIds);
    }
    
    /**
     * 测试静态资源访问
     */
    @GetMapping("/test-static")
    @ApiOperation("测试静态资源访问")
    public Result<String> testStaticAccess() {
        try {
            // 检查uploads目录是否存在
            File uploadsDir = new File("./uploads/generated-images/");
            if (!uploadsDir.exists()) {
                uploadsDir.mkdirs();
                log.info("创建uploads目录: {}", uploadsDir.getAbsolutePath());
            }
            
            // 列出目录中的文件
            File[] files = uploadsDir.listFiles();
            if (files != null && files.length > 0) {
                String firstFile = files[0].getName();
                String testUrl = "http://localhost:8080/uploads/generated-images/" + firstFile;
                log.info("测试静态资源URL: {}", testUrl);
                return Result.success("找到 " + files.length + " 个文件，测试URL: " + testUrl);
            } else {
                return Result.success("uploads目录存在但为空: " + uploadsDir.getAbsolutePath());
            }
        } catch (Exception e) {
            log.error("测试静态资源失败", e);
            return Result.fail("测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 切换示例图点赞状态
     */
    @PostMapping("/examples/{exampleId}/like")
    @ApiOperation("切换示例图点赞状态")
    public Result<Object> toggleExampleLike(@ApiParam("示例图ID") @PathVariable Long exampleId) {
        Long userId = UserContext.getCurrentUserId();
        log.info("User {} toggling like for example: {}", userId, exampleId);
        
        try {
            // 检查示例图是否存在
            AiImageExample example = exampleMapper.selectById(exampleId);
            if (example == null) {
                return Result.fail("示例图不存在");
            }
            
            // 检查是否已点赞
            AiImageExampleLike existingLike = exampleLikeMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<AiImageExampleLike>()
                    .eq("example_id", exampleId)
                    .eq("user_id", userId)
            );
            
            boolean liked;
            if (existingLike != null) {
                // 取消点赞
                exampleLikeMapper.deleteById(existingLike.getId());
                liked = false;
                
                // 更新点赞数
                if (example.getLikeCount() > 0) {
                    example.setLikeCount(example.getLikeCount() - 1);
                    exampleMapper.updateById(example);
                }
            } else {
                // 添加点赞
                AiImageExampleLike like = new AiImageExampleLike();
                like.setExampleId(exampleId);
                like.setUserId(userId);
                like.setCreateTime(java.time.LocalDateTime.now());
                exampleLikeMapper.insert(like);
                liked = true;
                
                // 更新点赞数
                example.setLikeCount(example.getLikeCount() + 1);
                exampleMapper.updateById(example);
            }
            
            // 返回点赞状态和数量
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("liked", liked);
            result.put("likeCount", example.getLikeCount());
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("切换示例图点赞失败", e);
            return Result.fail("操作失败");
        }
    }
}
